<template>
  <div>
    <div class="clearfix">
      <!--
        name    —— 向后端传递数据时会要用到
        action  —— 后端路径
    -->
      <a-upload
        name="image"
        v-model:file-list="fileList"
        list-type="picture-card"
        :headers="headers"
        :action="actionUrl"
        :progress="progress"
        :max-count="maxCount"
        :show-upload-list="false"
        class="avatar-uploader"
        @beforeUpload="beforeUpload"
        @preview="handlePreview"
        @change="handleChange"
        :customRequest="(file:any) => uploadFile(file)"
      >
        <div v-if="previewImage" class="relative w-[102px] h-[102px] learn-top-sub" @click.stop="() => {}">
          <a-image :src="previewImage" class="h-[102px]" />
          <div class="mask-img z-100 px-[15px]">
            <zoom-in-outlined class="text-[17px] cursor-pointer" @click.stop="() => (previewVisible = true)" />
            <delete-outlined class="text-[17px] cursor-pointer" @click.stop="handleDel" />
          </div>
        </div>
        <div v-else>
          <loading-outlined v-if="loading" />
          <plus-outlined v-else />
          <div class="ant-upload-text">点击上传图片</div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
    <div class="upload-tip">
      {{ storage.get('img_type') ? '支持' + storage.get('img_type') + '素材，' : '' }}
      {{ storage.get('img_size') ? storage.get('img_size') + '以内；' : '' }}建议尺寸{{ imgSizeRule }}
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, watch, inject } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadChangeParam, UploadProps } from 'ant-design-vue'
import apis from '@/apis'
import { storage } from '@/utils/storage'
const {
  permission: { upload }
} = apis
const fileList = ref([])
const emit = defineEmits(['getImageInfo'])
interface ImageInfo {
  maxCount?: number //设置最多可以上传的图片数量
  imgSrc: string
  fileUrl?: string //上传到后端的路径
  imgType: string
  imgSizeRule?: string
}
interface HeaderInfo {
  Authorization: string
}

const headers = reactive<HeaderInfo>({
  Authorization: 'Bearer ' + storage.get('token')
})
const props = withDefaults(defineProps<ImageInfo>(), {
  maxCount: 1,
  fileUrl: '',
  imgSrc: '',
  /**
  0: 杂项图片保存，不知道放哪里，就放在这里
  - 1: 视频相关图片
  - 2: 图集相关图片
  - 3: 文章小说相关图片
  - 4: 广告相关图片
  */
  imgType: '0',
  imgSizeRule: '150*84px'
})
const { maxCount, fileUrl, imgType, imgSrc } = toRefs(props)
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const baseUrl: any = inject('baseUrl')
const actionUrl = baseUrl + fileUrl.value
const getBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
const loading = ref(false)
const progress: UploadProps['progress'] = {
  strokeColor: {
    '0%': '#108ee9',
    '100%': '#87d068'
  },
  strokeWidth: 3,
  format: (percent: any) => `${parseFloat(percent.toFixed(2))}%`,
  class: 'test'
}
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.file)
  }
  previewImage.value = file.url || file.preview
}
const handleDel = () => {
  previewImage.value = ''
  fileList.value = []
  emit('getImageInfo', '')
  console.log(fileList.value)
}
const imageType = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
// 检查图片格式和图片大小
const beforeUpload = (file: any) => {
  //图片格式限制为 jpeg、png
  // const isJpgOrPng = imageType.includes(file.type)
  // if (!isJpgOrPng) {
  //   message.error('只支持后缀为 .jpg .jpeg .png .bmp .gif 的图片')
  // }
  //图片大小限制为 10M以内
  const isLimit = file.size / 1024 / 1024 <= storage.get('img_size')
  if (!isLimit) {
    return message.error(`图片大小不能超过${storage.get('img_size')}，请重新上传`)
  }
  // return isJpgOrPng && isLimit
  // return isLimit
}
const handleChange = (info: UploadChangeParam) => {
  console.log('info: ', info)
  const file = info.file as any
  const fileList = info.fileList as any
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }
  if (info.file.status === 'done') {
    console.log(file, fileList, 'fileData')
    message.success('上传成功')
  } else if (info.file.status === 'error') {
    emit('getImageInfo', undefined)
  }
  loading.value = false
}
const uploadFile = (file: any) => {
  // beforeUpload(file.file)//后端判断
  const formData = new FormData()
  formData.append('file', file.file)
  formData.append('img_type', imgType.value)
  upload(formData)
    .then((res: any) => {
      file.onSuccess()
      previewImage.value = baseUrl + res.data.url
      emit('getImageInfo', res.data.url)
    })
    .catch((error) => {
      file.onError()
    })
}
watch(
  () => imgSrc.value,
  (val: string) => {
    console.log('val: ', val)
    if (!val) return (previewImage.value = '')
    previewImage.value = baseUrl + val
  },
  { deep: true }
)
</script>

<style scoped>
.mask-img {
  position: absolute;
  width: 100%;
  height: 100%;
  bottom: 0;
  background: rgba(101, 101, 101, 0.6);
  color: #ffffff;
  opacity: 0;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.learn-top-sub:hover .mask-img {
  opacity: 1;
  cursor: default;
}

.clearfix {
  width: 104px;
  height: 104px;
  text-align: center;
  line-height: 104px;
  border-radius: 4px;
}

.anticon-plus {
  color: #c2c2c2;
}

.upload-tip {
  font-size: 12px;
  color: #bfbfbf;
  margin-top: 4px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  font-size: 12px;
  color: #bfbfbf;
}

.w-359 {
  width: 359px;
}

:deep(.ant-upload-list) {
  display: none;
}
</style>
